<?php
error_reporting("E_ALL");ini_set("display_errors", 1);
include("include/function.php");
include("include/OllamaClient.php");
$config = include("config.php");
include("include/".$config['DB_TYPE'].".class.php");
$db = new db;
$db->connect($config['DB_HOST'],$config['DB_USER'],$config['DB_PWD'],$config['DB_NAME'], $config['DB_PCONNECT']);

$post = $_GET;
$id = !empty($post['id'])?intval($post['id']):0;
$sql="select id,host,name,model,error from ollama_list where status=0 and is_delete=0 and id>".$id." order by id";
$info = $db->get_one($sql);if(empty($info))exit('over');
$startTime = microtime(true);
$ollama = new OllamaClient('http://'.$info['host'].'/api');
if(strpos('a'.$info['error'],'not support chat')>0 || strpos('a'.$info['model'],'embed')>0 || strpos('a'.$info['model'],'Embedding')>0 || strpos('a'.$info['model'],'bge-')>0 || strpos('a'.$info['model'],'all-minilm')>0){
    $response = $ollama->embed(array(
        'model' => $info['model'],
        "input"=> "Does Ollama support embedding models?"
    ));
    if(!empty($response['embeddings'])){
        $response['message']['content']='支持embedding models';unset($response['embeddings']);
    }
}else{
    $history = array(
        array('role' => 'user', 'content' => '你好'),
      //  array('role' => 'assistant', 'content' => '您好！有什么可以帮助您？')
    );
    $response = $ollama->chat(array(
        'model' => $info['model'],
        "messages"=> $history,
        "stream"=> false
    ));
}
$endTime = microtime(true);
$haoshi = ($endTime - $startTime)*1000;
echo $info['host'].'->'.$info['name'].'<br>耗时：'.$haoshi . 'ms<br>';
if ($response && isset($response['message']['content'])) {
    $content = removeEmojiAndSpecialChars($response['message']['content']);
    if(empty($content))$content=json_encode($response,JSON_UNESCAPED_UNICODE);
    echo "AI回复:<pre>" . $content;
    $db->query("update ollama_list set status=1,error='".addslashes($content)."',haoshi='".$haoshi."',updatetime=".time()." where id=".$info['id']);
}else if(!empty($response['error'])){
    $db->query("update ollama_list set status=2,error='".addslashes($response['error'])."',haoshi='".$haoshi."',updatetime=".time()." where id=".$info['id']);
    echo '不可用：'.$response['error'];
}else{
    if(empty($response))$response='超时了';
    if(is_array($response))$response = json_encode($response,JSON_UNESCAPED_UNICODE);
    var_dump($response);
    $db->query("update ollama_list set status=2,error='".addslashes($response)."',haoshi='".$haoshi."',updatetime=".time()." where id=".$info['id']);
    
}
if($info['id']){
    echo '<br>'.$info['id']."<script>location.href='?id=".$info['id']."'</script>";
}else{
    exit('over');
}